﻿/*********一些全局变量************/
var customerStatusData = [{AutoId:1,Name:'潜在'},{AutoId:2,Name:'正式'}];
var customerSourceData = [{ AutoId: '1', Name: '自然单' }, { AutoId: '2', Name: '关系单' }, { AutoId: '3', Name: '老客户' }, { AutoId: '4', Name: '异业' }
    , { AutoId: '5', Name: '活动转单' }, { AutoId: '6', Name: '设计师' }, { AutoId: '7', Name: '小区拓展' }, { AutoId: '8', Name: '工程单' }
    , { AutoId: '9', Name: '媒体引流' }, { AutoId: '10', Name: '线上引流' }, { AutoId: '11', Name: '名雕' }, { AutoId: '12', Name: '南国鼎峰' }];
var docState =  [{AutoId:'1',Name:'正常'},{AutoId:'2',Name:'已提审'},{AutoId:'3',Name:'已审核'}];
var payTypes = [{ AutoId: 1, Name: '招行9492' }, { AutoId: 2, Name: '总部代收款' }, { AutoId: 3, Name: '商场代收款' }, { AutoId: 4, Name: '联盟代收款' }
    , { AutoId: 5, Name: '其他代收款' }, { AutoId: 6, Name: '家装返利' }, { AutoId: 7, Name: '活动返现' }, { AutoId: 8, Name: '代金券' }];
var payPurpos = [{AutoId:1,Name:'定金'},{AutoId:2,Name:'货款'},{AutoId:3,Name:'尾款'}];
var otherType = [{AutoId:1,Name:'拆卸费用'},{AutoId:2,Name:'售后费用'},{AutoId:3,Name:'上楼费用'},{AutoId:4,Name:'量尺费用'},{AutoId:4,Name:'其他费用'}];
/***************部分控件进行扩展********************/

(function ($) {
    function pagerFilter(data) {
        if ($.isArray(data)) {    // is array
            data = {
                total: data.length,
                rows: data
            }
        }
        var target = this;
        var dg = $(target);
        var state = dg.data('datagrid');
        var opts = dg.datagrid('options');
        if (!state.allRows) {
            state.allRows = (data.rows);
        }
        if (!opts.remoteSort && opts.sortName) {
            var names = opts.sortName.split(',');
            var orders = opts.sortOrder.split(',');
            state.allRows.sort(function (r1, r2) {
                var r = 0;
                for (var i = 0; i < names.length; i++) {
                    var sn = names[i];
                    var so = orders[i];
                    var col = $(target).datagrid('getColumnOption', sn);
                    var sortFunc = col.sorter || function (a, b) {
                        return a == b ? 0 : (a > b ? 1 : -1);
                    };
                    r = sortFunc(r1[sn], r2[sn]) * (so == 'asc' ? 1 : -1);
                    if (r != 0) {
                        return r;
                    }
                }
                return r;
            });
        }
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = state.allRows.slice(start, end);
        return data;
    }
    var loadDataMethod = $.fn.datagrid.methods.loadData;
    var deleteRowMethod = $.fn.datagrid.methods.deleteRow;
    var insertRowMethod = $.fn.datagrid.methods.insertRow;
    $.extend($.fn.datagrid.methods, {
        clientPaging: function (jq) {
            return jq.each(function () {
                var dg = $(this);
                var state = dg.data('datagrid');
                var opts = state.options;
                opts.loadFilter = pagerFilter;
                var onBeforeLoad = opts.onBeforeLoad;
                opts.onBeforeLoad = function (param) {
                    state.allRows = null;
                    return onBeforeLoad.call(this, param);
                }
                var pager = dg.datagrid('getPager');
                pager.pagination({
                    onSelectPage: function (pageNum, pageSize) {
                        opts.pageNumber = pageNum;
                        opts.pageSize = pageSize;
                        pager.pagination('refresh', {
                            pageNumber: pageNum,
                            pageSize: pageSize
                        });
                        dg.datagrid('loadData', state.allRows);
                    }
                });
                $(this).datagrid('loadData', state.data);
                if (opts.url) {
                    $(this).datagrid('reload');
                }
            });
        },
        loadData: function (jq, data) {
            jq.each(function () {
                $(this).data('datagrid').allRows = null;
            });
            return loadDataMethod.call($.fn.datagrid.methods, jq, data);
        },
        setData: function (jq, data) {
            if ($.isArray(data)) {    // is array
                data = {
                    total: data.length,
                    rows: data
                }
            }
            jq.each(function () {
                $(this).data('datagrid').allRows = data.rows;
            });
        },
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat($(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    if(col.editor!=null){
                        col.editor1 = col.editor;
                    }
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                var ed = $(this).datagrid('getEditor', param);
                if (ed) {
                    switch(ed.type){
                        default:
                            $(ed.target).focus();
                            break;
                        case "textbox":
                            $(ed.target).textbox('textbox').focus();
                            break;
                        case "numberbox":
                            $(ed.target).numberbox('textbox').focus();
                            break;
                        case "combogrid":
                            $(ed.target).combo('showPanel');
                            break;
                        case "combobox":
                            $(ed.target).combo('showPanel');
                            break;
                        case "datebox":
                            $(ed.target).combo('showPanel');
                            break;
                   }
                }
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        },
        enableCellEditing: function (jq) {
            return jq.each(function () {
                var dg = $(this);
                var opts = dg.datagrid('options');
                opts.oldOnClickCell = opts.onClickCell;
                opts.onClickCell = function (index, field) {
                    if (opts.editIndex != undefined) {
                        if (dg.datagrid('validateRow', opts.editIndex)) {
                            dg.datagrid('endEdit', opts.editIndex);
                            opts.editIndex = undefined;
                        } else {
                            return;
                        }
                    }
                    dg.datagrid('selectRow', index).datagrid('editCell', {
                        index: index,
                        field: field
                    });
                    opts.editIndex = index;
                    if (opts.oldOnClickCell != null) {
                        opts.oldOnClickCell.call(this, index, field);
                    }
                }
            });
        },
		disableCellEditing: function(jq){
				return jq.each(function(){
					var dg = $(this);
					var opts = dg.datagrid('options');
                    if(opts.oldOnClickCell!=undefined){
                        opts.onClickCell = opts.oldOnClickCell;
                        opts.oldOnClickCell = null;
                    }
			});
		},
        deleteRow: function (jq, index) {
            return jq.each(function () {
                var row = $(this).datagrid('getRows')[index];
                deleteRowMethod.call($.fn.datagrid.methods, $(this), index);
                var state = $(this).data('datagrid');
                if (state.options.loadFilter == pagerFilter) {
                    for (var i = 0; i < state.allRows.length; i++) {
                        if (state.allRows[i] == row) {
                            state.allRows.splice(i, 1);
                            break;
                        }
                    }
                    $(this).datagrid('loadData', state.allRows);
                }
            });
        },
		loading: function(jq){
			return jq.each(function(){
				$(this).datagrid("getPager").pagination("loading");
				var opts = $(this).datagrid("options");
				var wrap = $.data(this,"datagrid").panel;
				if(opts.loadMsg){
					$("<div class=\"datagrid-mask\"></div>").css({display:"block",width:wrap.width(),height:wrap.height()}).appendTo(wrap);
					$("<div class=\"datagrid-mask-msg\"></div>").html(opts.loadMsg).appendTo(wrap).css({display:"block",left:(wrap.width()-$("div.datagrid-mask-msg",wrap).outerWidth())/2,top:(wrap.height()-$("div.datagrid-mask-msg",wrap).outerHeight())/2});
				}
			});
		},
		loaded: function(jq){
			return jq.each(function(){
				$(this).datagrid("getPager").pagination("loaded");
				var wrap = $.data(this,"datagrid").panel;
				wrap.find("div.datagrid-mask-msg").remove();
				wrap.find("div.datagrid-mask").remove();
			});
		},
        insertRow: function (jq, param) {
            return jq.each(function () {
                var row = param.row;
                insertRowMethod.call($.fn.datagrid.methods, $(this), param);
                var state = $(this).data('datagrid');
                state.allRows.splice(param.index, 0, param.row);
                $(this).datagrid('loadData', state.allRows);
            });
        },
        getAllRows: function (jq) {
            var rows = jq.data('datagrid').allRows;
            return rows;
        }
    })
})(jQuery);
$.extend($.fn.datagrid.defaults.editors, {
	combogrid: {
		init: function (container, options) {
			var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
			input.combogrid(options);           
			return input;
		},
		destroy: function (target) {
			$(target).combogrid('destroy');
		},
		getValue: function (target) {
			return $(target).combogrid('getValue');
		},
		setValue: function (target, value) {
			$(target).combogrid('setValue', value);
		},
		resize: function (target, width) {
			$(target).combogrid('resize', width);
		}
	}
});


/***************全局方法****************/
function showMask(message) {
    var mask_bg = document.createElement("div");
    mask_bg.id = "mask_bg";
    mask_bg.style.position = "absolute";
    mask_bg.style.top = "0px";
    mask_bg.style.left = "0px";
    mask_bg.style.width = "100%";
    mask_bg.style.height = "100%";
    mask_bg.style.backgroundColor = "#777";
    mask_bg.style.opacity = 0.6;
    mask_bg.style.zIndex = 10001;
    document.body.appendChild(mask_bg);
    var mask_msg = document.createElement("div");
    mask_msg.style.position = "absolute";
    mask_msg.style.top = "35%";
    mask_msg.style.left = "42%";
    mask_msg.style.backgroundColor = "white";
    mask_msg.style.border = "#336699 1px solid";
    mask_msg.style.textAlign = "center";
    mask_msg.style.fontSize = "1.1em";
    mask_msg.style.fontWeight = "bold";
    mask_msg.style.padding = "0.5em 3em 0.5em 3em";
    mask_msg.style.zIndex = 10002;
    if(!message){
        mask_msg.innerText = "请稍侯...";
    }else{
        mask_msg.innerText = "请稍侯...";
    }
    mask_bg.appendChild(mask_msg);
}
function hideMask() {
    var mask_bg = document.getElementById("mask_bg");
    if (mask_bg != null)
        mask_bg.parentNode.removeChild(mask_bg);
}
function addTab(moduleId,title, url,arg) {
    var jq = top.jQuery;
    if (jq('#mainFrame').tabs('exists', title)) {
        jq('#mainFrame').tabs('select', title);
    } else {
        if(!arg){
            arg='';
        }
        var content = '<iframe scrolling="no" height="100%" width="100%" src="'+url+'?moduleid=app_'+moduleId+arg+'"  id="app_' + moduleId + '"  frameborder="0" ></iframe>';
        var panel = {
            title: title,
            content: content,
            closable: true,
            fit: true
        }
        jq('#mainFrame').tabs('add', panel);
    }
}
function GetQueryString(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}
function dateFormatter(date){
    if(!date||!(date instanceof Date)){return '';}
    var y = date.getFullYear();
    var m = date.getMonth()+1;
    var d = date.getDate();
    return y+'/'+(m<10?('0'+m):m)+'/'+(d<10?('0'+d):d);
}
function dateParser(s){
    if (!s) return new Date();
    var ss = (s.split('/'));
    var y = parseInt(ss[0],10);
    var m = parseInt(ss[1],10);
    var d = parseInt(ss[2],10);
    if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
        return new Date(y,m-1,d);
    } else {
        return new Date();
    }
}
function doSearch(q,data,searchList,ele){ 
    ele.combogrid('grid').datagrid('loadData', []); 
    if(q == ""){ 
        ele.combogrid('grid').datagrid('loadData', data); 
        return; 
    } 
    var rows = []; 
	
    $.each(data,function(i,obj){ 
        for(var p in searchList){ 
            var v = obj[searchList[p]]; 
            if (!!v && v.toString().indexOf(q) >= 0){ 
                rows.push(obj); 
                break; 
            } 
        } 
    }); 
    if(rows.length == 0){ 
		console.log('过滤器搜索不到任何条件');
        ele.combogrid('grid').datagrid('loadData', []); 
        return; 
    } 
    ele.combogrid('grid').datagrid('loadData', rows.slice(0, 50)); 
} 
function valToName(dataSource,val){
    if(val==0){
        return '';
    }
	for(var i=0;i<dataSource.length;i++){
		if(dataSource[i].AutoId == val){
			return dataSource[i].Name;
		}
	}
	return val;
}
function dataFetcher(api){
    var ajaxAsyncState = $.ajaxSettings.async;
    $.ajaxSettings.async=false;
    var result=null;
	console.log('开始向'+api+'中获取数据');
    $.get(api, function (data) {
        if (data.Result == 0) {
            result = JSON.parse(data.Data);
			console.log('dataFetcher函数已在'+api+'中获得'+result.length+'笔数据');
        }
    }, "json")
    .error(function () {
        $.messager.alert("错误", "系统内部错误", "error");
    });
    $.ajaxSettings.async=ajaxAsyncState;
	console.log('向调用方返回数据');
    return result;
}
function pagerFilter(data){
	if ($.isArray(data)){	// is array
		data = {
			total: data.length,
			rows: data
		}
	}
	var target = this;
	var dg = $(target);
	var state = dg.data('datagrid');
	var opts = dg.datagrid('options');
	if (!state.allRows){
		state.allRows = (data.rows);
	}
	if (!opts.remoteSort && opts.sortName){
		var names = opts.sortName.split(',');
		var orders = opts.sortOrder.split(',');
		state.allRows.sort(function(r1,r2){
			var r = 0;
			for(var i=0; i<names.length; i++){
				var sn = names[i];
				var so = orders[i];
				var col = $(target).datagrid('getColumnOption', sn);
				var sortFunc = col.sorter || function(a,b){
					return a==b ? 0 : (a>b?1:-1);
				};
				r = sortFunc(r1[sn], r2[sn]) * (so=='asc'?1:-1);
				if (r != 0){
					return r;
				}
			}
			return r;
		});
	}
	var start = (opts.pageNumber-1)*parseInt(opts.pageSize);
	var end = start + parseInt(opts.pageSize);
	data.rows = state.allRows.slice(start, end);
	return data;
}
function getDepartment(withCache){
    if(!withCache){
       sessionStorage.removeItem('department_cache');
    }
    if(sessionStorage['department_cache']==null){
		var dataObj = dataFetcher('../../api/department/list');
		if(dataObj!=null){
			sessionStorage['department_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得部门数据');
    }
    return JSON.parse(sessionStorage['department_cache']);
}
function getTitle(withCache){
    if(!withCache){
       sessionStorage.removeItem('title_cache');
    }
    if(sessionStorage['title_cache']==null){
		var dataObj = dataFetcher('../../api/title/list');
		if(dataObj!=null){
			sessionStorage['title_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得TITLE数据');
    }
    return JSON.parse(sessionStorage['title_cache']);
}
function getProduction(withCache){
    if(!withCache){
       sessionStorage.removeItem('production_cache'); 
    }
    if(sessionStorage['production_cache']==null){
		var dataObj = dataFetcher('../../api/production/list');
		if(dataObj!=null){
			sessionStorage['production_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得产品数据');
    }
    return JSON.parse(sessionStorage['production_cache']);
}
function getBank(withCache){
    if(!withCache){
       sessionStorage.removeItem('bank_cache'); 
    }
    if(sessionStorage['bank_cache']==null){
		var dataObj = dataFetcher('../../api/bank/list');
		if(dataObj!=null){
			sessionStorage['bank_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得产品数据');
    }
    return JSON.parse(sessionStorage['bank_cache']);
}
function getEmployee(withCache){
    if(!withCache){
       sessionStorage.removeItem('employee_cache');
    }
    if(sessionStorage['employee_cache']==null){
		var dataObj = dataFetcher('../../api/employee/list');
		if(dataObj!=null){
			sessionStorage['employee_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得人员数据');
    }
    return JSON.parse(sessionStorage['employee_cache'] );
}
function getUser(withCache){
    if(!withCache){
       sessionStorage.removeItem('user_cache');
    }
    if(sessionStorage['user_cache']==null){
		var dataObj = dataFetcher('../../api/user/list');
		if(dataObj!=null){
			sessionStorage['user_cache'] = JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得用户数据');
    }
    return JSON.parse(sessionStorage['user_cache']);
}
function getBland(withCache){
    if(!withCache){
       sessionStorage.removeItem('bland_cache');
    }
    if(sessionStorage['bland_cache']==null){
		var dataObj = dataFetcher('../../api/bland/list');
		if(dataObj!=null){
			sessionStorage['bland_cache'] = JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得品牌数据');
    }
    return JSON.parse(sessionStorage['bland_cache']);
}
function getSeries(withCache){
    if(!withCache){
       sessionStorage.removeItem('series_cache');
    }
    if(sessionStorage['series_cache']==null){
		var dataObj = dataFetcher('../../api/series/list');
		if(dataObj!=null){
			sessionStorage['series_cache'] = JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得系列数据');
    }
    return JSON.parse(sessionStorage['series_cache'] );
}
function getRegion(withCache){
    if(!withCache){
       sessionStorage.removeItem('region_cache');
    }
    if(sessionStorage['region_cache']==null){
		var dataObj = dataFetcher('../../api/region/list');
		if(dataObj!=null){
			sessionStorage['region_cache']= JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得区域数据');
    }
    return JSON.parse(sessionStorage['region_cache']);
}
function getOrderType(withCache){
    if(!withCache){
       sessionStorage.removeItem('ordertype_cache');
    }
    if(sessionStorage['ordertype_cache']==null){
		var dataObj = dataFetcher('../../api/order/listtype');
		if(dataObj!=null){
			sessionStorage['ordertype_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得订单类别数据');
    }
    return JSON.parse(sessionStorage['ordertype_cache']);
}
function getUnit(withCache){
    if(!withCache){
       sessionStorage.removeItem('unit_cache');
    }
    if(sessionStorage['unit_cache']==null){
		var dataObj = dataFetcher('../../api/unit/list');
		if(dataObj!=null){
			sessionStorage['unit_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得单位数据');
    }
    return JSON.parse(sessionStorage['unit_cache'] );
}
function getUnitGroup(withCache){
    if(!withCache){
       sessionStorage.removeItem('gunittype_cache');
    }
    if(sessionStorage['gunittype_cache']==null){
		var dataObj = dataFetcher('../../api/unit/glist');
		if(dataObj!=null){
			sessionStorage['gunittype_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得订单类别数据');
    }
    return JSON.parse(sessionStorage['gunittype_cache'] );
}
function getProductionType(withCache){
    if(!withCache){
       sessionStorage.removeItem('productiontype_cache');
    }
    if(sessionStorage['productiontype_cache']==null){
		var dataObj = dataFetcher('../../api/production/listtype');
		if(dataObj!=null){
			sessionStorage['productiontype_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得产品类型数据');
    }
    return JSON.parse(sessionStorage['productiontype_cache'] );
}
function getSalesPoint(withCache){
    if(!withCache){
       sessionStorage.removeItem('salespoint_cache');
    }
    if(sessionStorage['salespoint_cache']==null){
		var dataObj = dataFetcher('../../api/salespoint/list');
		if(dataObj!=null){
			sessionStorage['salespoint_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得门店数据');
    }
    return JSON.parse(sessionStorage['salespoint_cache'] );
}
function getCustomer(withCache){
    if(!withCache){
       sessionStorage.removeItem('customer_cache');
    }
    if(sessionStorage['customer_cache']==null){
		var dataObj = dataFetcher('../../api/customer/list');
		if(dataObj!=null){
			sessionStorage['customer_cache']=JSON.stringify(dataObj);
			return dataObj;
		}else{
			return null;
		}
    }else{
        console.log('从本地缓存中取得客户数据');
    }
    return JSON.parse(sessionStorage['customer_cache'] );
}
function getAutoCode(moduleCode){
    var ajaxAsyncState = $.ajaxSettings.async;
    $.ajaxSettings.async=false;
    var result=null;
    $.get('../../api/codegenerator/gen?code='+moduleCode, function (data) {
        if (data.Result == 0) {
            result = data.Data;
        }
    }, "json")
    .error(function () {
        $.messager.alert("错误", "系统内部错误", "error");
    });
    $.ajaxSettings.async=ajaxAsyncState;
    return result;
}
function getComboGridInfo(title, textField, columns, dataSource, onChange) {
    var searchList = [];
	for(var i=0;i<columns[0].length;i++){
		searchList.push(columns[0][i].field);
    }
	var comboGrid = new Object();
	comboGrid.data = dataSource.slice(0,50);
	comboGrid.panelWidth = 500;
	if(title){
		comboGrid.label = title+':';
	}
	comboGrid.idField = 'AutoId';
	comboGrid.textField = textField;
	comboGrid.keyHandler= {
		up: function(){},
		down: function(){},
		enter: function(){},
		query: function(q){doSearch(q,dataSource,searchList,$(this));$(this).textbox('setValue',q);}
	}
	//comboGrid.delay = 500;
	comboGrid.filter = function(q,row){  
		var opts = $(this).combogrid('options');
		return row[opts.textField].indexOf(q) == 0;
    };
    comboGrid.onShowPanel = function () {
        var value = $(this).combogrid('getValue');
        if (value != "") {
            for (var i = 0; i < dataSource.length; i++) {
                if (value == dataSource[i].AutoId) {
                    var ds = [dataSource[i]];
                    $(this).combogrid('grid').datagrid('loadData', ds); 
                    break;
                }
            }
        }
    };
    comboGrid.onHidePanel = function () {
        var t = $(this).combogrid('getValue');
		var selectRow = $(this).combogrid('grid').datagrid('getSelected');
        if ((selectRow == null || t != selectRow.AutoId) && $(this).combogrid('getValue')!="") {
			$.messager.alert('警告','不允许直接输入');
			$(this).combogrid('setValue', '');
		}
	};
	comboGrid.columns = columns;
	if(onChange){
		comboGrid.onChange = onChange;
    }
	return comboGrid;
}
function stateFormatter(value,row,index){
	switch(value){
		default:
			return '创建中';
			break;
		case 1:
			return '正常';
			break;
		case 2:
			return '已提审';
			break;
		case 3:
			return '已审核';
			break;
		case 4:
			return '已确认';
			break;
	}
}
function numberFormat(number, decimals, dec_point, thousands_sep) {
    /*
    * 参数说明：
    * number：要格式化的数字
    * decimals：保留几位小数
    * dec_point：小数点符号
    * thousands_sep：千分位符号
    * */
    number = (number + '').replace(/[^0-9+-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.ceil(n * k) / k;
        };
 
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    var re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
    }
 
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
function getEmployeeBySalesPoint(){
    var ajaxAsyncState = $.ajaxSettings.async;
    $.ajaxSettings.async = false;
    var employeesInSP = [];
    var employees = getEmployee();
    $.get('../../api/salespoint/listemployees?spid='+customer.SalesPointId,function(data){
        if(data.Result==0){
            var emp = JSON.parse(data.Data);
            for(var i=0;i<emp.length;i++){
                for(var j=0;j<employees.length;j++){
                    if(employees[j].AutoId == emp[i].EmployeeId){
                        employeesInSP.push(employees[j]);
                    }
                }
            }
        }else{
            
        }
    },'json');
    $.ajaxSettings.async = ajaxAsyncState;
    return employeesInSP;
}
function updateBtnState(state,twice){
    switch(state){
        default:
            $('#detailSave').linkbutton({disabled:false});
            $('#btnSubmit').linkbutton({disabled:true});
            $('#detailDel').linkbutton({disabled:false});
            $('#btnRecall').linkbutton({disabled:true});
            $('#btnApprove').linkbutton({disabled:true});
            $('#btnReject').linkbutton({disabled:true});
            $('#btnRevert').linkbutton({disabled:true});
			if(twice){
				$('#_detailSave').linkbutton({disabled:true});
				$('#_btnSubmit').linkbutton({disabled:true});
				$('#_detailDel').linkbutton({disabled:true});
				$('#_btnRecall').linkbutton({disabled:true});
				$('#_btnApprove').linkbutton({disabled:true});
				$('#_btnReject').linkbutton({disabled:true});
				$('#_btnRevert').linkbutton({disabled:true});
			}
            break;
        case 1:
            $('#detailSave').linkbutton({disabled:false});
            $('#btnSubmit').linkbutton({disabled:false});
            $('#detailDel').linkbutton({disabled:false});
            $('#btnRecall').linkbutton({disabled:true});
            $('#btnApprove').linkbutton({disabled:true});
            $('#btnReject').linkbutton({disabled:true});
            $('#btnRevert').linkbutton({disabled:true});
			if(twice){
				$('#_detailSave').linkbutton({disabled:false});
				$('#_btnSubmit').linkbutton({disabled:false});
				$('#_detailDel').linkbutton({disabled:false});
				$('#_btnRecall').linkbutton({disabled:true});
				$('#_btnApprove').linkbutton({disabled:true});
				$('#_btnReject').linkbutton({disabled:true});
				$('#_btnRevert').linkbutton({disabled:true});
			}
            break;
        case 2:
				$('#detailSave').linkbutton({disabled:true});
				$('#btnSubmit').linkbutton({disabled:true});
				$('#detailDel').linkbutton({disabled:true});
				$('#btnRecall').linkbutton({disabled:false});
				$('#btnApprove').linkbutton({disabled:false});
				$('#btnReject').linkbutton({disabled:false});
				$('#btnRevert').linkbutton({disabled:true});
			if(twice){
				$('#_detailSave').linkbutton({disabled:true});
				$('#_btnSubmit').linkbutton({disabled:true});
				$('#_detailDel').linkbutton({disabled:true});
				$('#_btnRecall').linkbutton({disabled:false});
				$('#_btnApprove').linkbutton({disabled:false});
				$('#_btnReject').linkbutton({disabled:false});
				$('#_btnRevert').linkbutton({disabled:true});
			}
            break;
        case 3:
            $('#detailSave').linkbutton({disabled:true});
            $('#btnSubmit').linkbutton({disabled:true});
            $('#detailDel').linkbutton({disabled:true});
            $('#btnRecall').linkbutton({disabled:true});
            $('#btnApprove').linkbutton({disabled:true});
            $('#btnReject').linkbutton({disabled:true});
            $('#btnRevert').linkbutton({disabled:false});
			if(twice){
				$('#_detailSave').linkbutton({disabled:true});
				$('#_btnSubmit').linkbutton({disabled:true});
				$('#_detailDel').linkbutton({disabled:true});
				$('#_btnRecall').linkbutton({disabled:true});
				$('#_btnApprove').linkbutton({disabled:true});
				$('#_btnReject').linkbutton({disabled:true});
				$('#_btnRevert').linkbutton({disabled:false});
			}
            break;					
        case 4:
            $('#btnDelete').linkbutton({disabled:true});
            $('#btnSubmit').linkbutton({disabled:true});
            $('#btnRecall').linkbutton({disabled:true});
            $('#btnApprove').linkbutton({disabled:true});
            $('#btnReject').linkbutton({disabled:true});
            $('#btnRevert').linkbutton({disabled:true});
			if(twice){
				$('#_detailSave').linkbutton({disabled:true});
				$('#_btnSubmit').linkbutton({disabled:true});
				$('#_detailDel').linkbutton({disabled:true});
				$('#_btnRecall').linkbutton({disabled:true});
				$('#_btnApprove').linkbutton({disabled:true});
				$('#_btnReject').linkbutton({disabled:true});
				$('#_btnRevert').linkbutton({disabled:true});
			}
            break;
    }
}
function moneyFormatter(val,row){
    return '￥'+numberFormat(val,2,'.',',');
}

function JSONToExcelConvertor(JSONData, FileName, title, filter) {
    if (!JSONData)
        return;
    //转化json为object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

    var excel = "<table>";

    //设置表头  
    var row = "<tr>";

    if (title) {
        //使用标题项
        for (var i in title) {
            row += "<th align='center'>" + title[i] + '</th>';
        }

    }
    else {
        //不使用标题项
        for (var i in arrData[0]) {
            row += "<th align='center'>" + i + '</th>';
        }
    }

    excel += row + "</tr>";

    //设置数据  
    for (var i = 0; i < arrData.length; i++) {
        var row = "<tr>";

        for (var index in arrData[i]) {
            //判断是否有过滤行
            if (filter) {
                if (filter.indexOf(index) == -1) {
                    var value = arrData[i][index] == null ? "" : arrData[i][index];
                    row += '<td>' + value + '</td>';
                }
            }
            else {
                var value = arrData[i][index] == null ? "" : arrData[i][index];
                row += "<td align='center'>" + value + "</td>";
            }
        }

        excel += row + "</tr>";
    }

    excel += "</table>";

    var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
    excelFile += '; charset=UTF-8">';
    excelFile += "<head>";
    excelFile += "<!--[if gte mso 9]>";
    excelFile += "<xml>";
    excelFile += "<x:ExcelWorkbook>";
    excelFile += "<x:ExcelWorksheets>";
    excelFile += "<x:ExcelWorksheet>";
    excelFile += "<x:Name>";
    excelFile += "{worksheet}";
    excelFile += "</x:Name>";
    excelFile += "<x:WorksheetOptions>";
    excelFile += "<x:DisplayGridlines/>";
    excelFile += "</x:WorksheetOptions>";
    excelFile += "</x:ExcelWorksheet>";
    excelFile += "</x:ExcelWorksheets>";
    excelFile += "</x:ExcelWorkbook>";
    excelFile += "</xml>";
    excelFile += "<![endif]-->";
    excelFile += "</head>";
    excelFile += "<body>";
    excelFile += excel;
    excelFile += "</body>";
    excelFile += "</html>";


    var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);

    var link = document.createElement("a");
    link.href = uri;

    link.style = "visibility:hidden";
    link.download = FileName + ".xls";

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
function exportData(url,searchArg) {
    $.get(url, { Args: searchArg, Length: 10000, Pos: 0 }, function (data) {
        if (data.Result == 0) {
            JSONToExcelConvertor(JSON.parse(data.Data), "数据导出");
        } else {
            $.messager.alert('提示', data.Message, 'error');
        }
    }, 'json');
}

function getInnDesigner(employees){
    var result = [];
    for(var i=0;i<employees.length;i++){
        if(employees[i].DepartmentId == 18){
            result.push(employees[i]);
        }
    }
    return result;
}
function getOutDesigner(employees){
    var result = [];
    for(var i=0;i<employees.length;i++){
        if(employees[i].DepartmentId == 17){
            result.push(employees[i]);
        }
    }
    return result;
}
function getSalesVIP(employees){
    var result = [];
    for(var i=0;i<employees.length;i++){
        if(employees[i].DepartmentId == 17){
            result.push(employees[i]);
        }
    }
    return result;
}